package com.iqiao.common.security;

import com.iqiao.common.util.json.JsonUtil;
import com.iqiao.common.web.result.JsonResult;
import com.iqiao.common.web.result.ReturnCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by flt on 2017/10/31.
 */
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        JsonResult result = new JsonResult(ReturnCode.NOT_LOGIN, "Authentication Failed");
        out.write(JsonUtil.toJson(result));

//        response.setStatus(HttpStatus.UNAUTHORIZED.value());
//        response.sendError(401, "Authentication Failed: " + exception.getMessage());
    }
}
